import express from 'express';
import asyncHandler from 'express-async-handler';

import { ParameterDto, ProductPageQuery } from '../../domain/model/product/dtos/index';

import { SimulationParameter } from '../../domain/model/simulation/type';
import { ParameterValidatorFactory, ValidatorType } from '../../domain/model/product/validator/validatorFactory';
import { ParameterService } from '../../domain/model/product/service/parameterService';
import { ProductService } from '../../domain/model/product/service/productService';

export function init(app: express.Application) {

  app.get('/api/products/:productName/parameters', asyncHandler(async (req, res) => {
    const productName = req.params['productName'];
    const parameters: ParameterDto[] = await new ParameterService().findByProduct(productName);
    res.json({ success: true, parameters });
  }));

  app.post('/api/products/:productName/parameters/validation', asyncHandler(async (req, res) => {
    const productNameOfPath = req.params['productName'];
    const { productName, parameters } = req.body;

    if (productNameOfPath === productName) {
      const validator = ParameterValidatorFactory.createValidator(ValidatorType.DATABASE);
      const validationResults = await validator.validate(productName, parameters as SimulationParameter[]);

      res.json({ success: true, validationResults });
    } else {
      res.json({ success: false, message: 'request path and request body are mismatched' });
    }
  }));

  app.post('/api/products/:productName/parameters', asyncHandler(async (req, res) => {
    const parameterId = await new ParameterService().saveOrUpdateByProductAndName(req.body as ParameterDto);
    res.json({ success: true, parameterId });
  }));

  app.post('/api/products/page', asyncHandler(async (req, res) => {
    const productPageQuery: ProductPageQuery = req.body;
    let products = await new ProductService().findForPage(productPageQuery);
    res.json({
      success: true,
      data: products
    });
  }));

}